package scatter.generator.component;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import scatter.common.rest.tools.StringTool;
import scatter.generator.core.Utils;

import java.io.File;

/**
 * 主要实现过程：
 * 1. 将 componentstarter 组件复制到临时目前
 * 2. 将复制完成的按新的组件名称替换修整
 * 3. 将修整完成的得到了目前路径
 * Created by yangwei
 * Created at 2020/8/20 12:46
 */
@Slf4j
@Data
public class ComponentGenerator {

    private static String componentstarter = "componentstarter";
    private static String Componentstarter = "Componentstarter";
    private static String ComponentStarter = "ComponentStarter";
    private static String componentStarter = "componentStarter";
    private static String componentstarter_server = "componentstarter-server";

    private String componentName = "";
    private String position = "components";
    // 是否包含server
    private boolean includeServer = false;


    public ComponentGenerator(String componentName, String position) {
        this.componentName = componentName;
        this.position = position;
    }

    /**
     * 主要是将模板重复到临时目录
     * @return
     */
    public  String before() {

        // E:\gitee-source\scatter
        String userDir = System.getProperty("user.dir");
        log.info("userDir = [" + userDir + "]");

        String starterPath = userDir + "/components/" + componentstarter;
        log.info("starterPath = [" + starterPath + "]");

        String tempPath = FileUtil.getTmpDirPath();
        log.info("tempPath = [" + tempPath + "]");

        String newTempStarterPath = tempPath + componentstarter;
        log.info("newTempStarterPath = [" + newTempStarterPath + "]");
        FileUtil.del(newTempStarterPath);
        FileUtil.del(FileUtil.getParent(newTempStarterPath,1) + "/" + componentName);


        FileUtil.copy(starterPath, tempPath, true);
        log.info("复制到临时目录完成");



        return newTempStarterPath;
    }

    /**
     * 生成的入口方法
     */
    public void generate() {
        // componentstarter 路径
        String newTempStarterPath = before();

        handle(newTempStarterPath);
        FileUtil.rename(new File(newTempStarterPath), componentName, false, false);

        String userDir = System.getProperty("user.dir");

        String tempPath = FileUtil.getTmpDirPath();
        String overWrite = tempPath + "componentGeneratorOverWrite.txt";

        String newPath = userDir + "/" + position;
        if (FileUtil.exist(newPath + "/" + componentName)) {
            if(!FileUtil.exist(overWrite)){
                FileUtil.touch(overWrite);
                throw new RuntimeException("组件已存在，请确认是否重复，如果确认覆盖请再次执行即可");
            }
        }

        FileUtil.copy(FileUtil.getParent(newTempStarterPath,1) + "/" + componentName, newPath, true);

        FileUtil.del(overWrite);
    }
    /**
     * 处理修整
     * @param path
     */
    public void handle(String path) {

        log.info("处理" + path);
        if (!FileUtil.exist(path)) {
            log.warn("handle 路径不存在已忽略,path = {}",path);
            return;
        }

        File[] ls = FileUtil.ls(path);
        if(ls == null || ls.length == 0){
            return;
        }
        for (File file : ls) {
            String absolutePath = FileUtil.getAbsolutePath(file);
            if (file.isDirectory()) {
                if("target".equals(file.getName())){
                    FileUtil.del(file);
                    continue;
                }
                if (!includeServer && componentstarter_server.equals(file.getName())) {
                    FileUtil.del(file);
                    continue;
                }
                // 目录都是小写
                if (file.getName().contains(componentstarter)) {
                    renameDirectory(file);

                    handle(path);
                    return;
                }else {
                    handle(absolutePath);
                }
            }else{
                if(file.getName().endsWith(".iml")){
                    FileUtil.del(file);
                }else{

                    replaceFileContent(file);
                    // 文件
                    renameFile(file);
                }

            }
        }

        log.info("处理" + path + "完成");
    }

    /**
     * 重命名目录
     * @param file
     */
    public void renameDirectory(File file) {
        String fileName = file.getName();
        if(fileName.contains(componentstarter) || fileName.contains(Componentstarter)) {
            // src父级目录一般是模块
            FileUtil.rename(file,
                    !file.getAbsolutePath().contains("/src/") ? fileName.replace(componentstarter,componentName) :
                    fileName.replace(componentstarter, Utils.componentNameConvertToUnderLine(componentName).replace("_","")), false, true);

        }
    }

    /**
     * 重命名文件
     * @param file
     */
    public void renameFile(File file) {
        String fileName = file.getName();
        if (fileName.contains(componentstarter + "-data") || fileName.contains(componentstarter + "-schema")) {
            FileUtil.rename(file, fileName.replace(componentstarter, componentName)
                    , false, true);
            return;
        }
        if(fileName.contains(componentstarter) || fileName.contains(Componentstarter)|| fileName.contains(ComponentStarter)|| fileName.contains(componentStarter)) {
            FileUtil.rename(file, fileName.replace(componentstarter, Utils.componentNameConvertToNoLine(componentName))
                    .replace(Componentstarter,StrUtil.upperFirst(Utils.componentNameConvertToNoLine(componentName)))
                    .replace(ComponentStarter,StrUtil.upperFirst(StringTool.lineToHump(Utils.componentNameConvertToUnderLine(componentName))))
                    .replace(componentStarter,StringTool.lineToHump(Utils.componentNameConvertToUnderLine(componentName)))
                    , false, true);

        }
    }

    /**
     * 多参数文件内容替换
     * @param file
     */
    public void replaceFileContent(File file) {

        if (!file.exists()) {
            log.info("replaceFileContent 路径不存在已忽略,filePath = ["+ file.getAbsolutePath() +"]");
            return;
        }

        String content = FileUtil.readUtf8String(file);
        String fileName = file.getName();
        if (fileName.endsWith("pom.xml")) {
            content = content.replace(componentstarter, componentName)
            .replace("<artifactId>components</artifactId>","<artifactId>"+ position +"</artifactId>");
        } else {
            content = content.replace(componentstarter, Utils.componentNameConvertToNoLine(componentName))
            .replace(Componentstarter,StrUtil.upperFirst(Utils.componentNameConvertToNoLine(componentName)))
            .replace(ComponentStarter,StrUtil.upperFirst(StringTool.lineToHump(Utils.componentNameConvertToUnderLine(componentName))))
            .replace(componentStarter,StringTool.lineToHump(Utils.componentNameConvertToUnderLine(componentName)))
            ;
        }
        FileUtil.writeUtf8String(content,file);
    }

}
